import { defineStore } from 'pinia'
import type { DeviceType } from '@/types'
import { detectDeviceType } from '@/utils/device'

export const useAppStore = defineStore('app', () => {
  // 设备类型
  const deviceType = ref<DeviceType>(detectDeviceType())
  
  // 加载状态
  const loading = ref(false)
  
  // 当前选中的日期
  const selectedDate = ref(new Date())
  
  // 侧边栏状态（桌面端）
  const sidebarCollapsed = ref(false)
  
  // 计算属性
  const isMobile = computed(() => deviceType.value === 'mobile')
  const isDesktop = computed(() => deviceType.value === 'desktop')
  
  // 方法
  const setDeviceType = (type: DeviceType) => {
    deviceType.value = type
  }
  
  const setLoading = (state: boolean) => {
    loading.value = state
  }
  
  const setSelectedDate = (date: Date) => {
    selectedDate.value = date
  }
  
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }
  
  // 监听窗口大小变化
  const updateDeviceType = () => {
    setDeviceType(detectDeviceType())
  }
  
  // 初始化
  const init = () => {
    window.addEventListener('resize', updateDeviceType)
  }
  
  const destroy = () => {
    window.removeEventListener('resize', updateDeviceType)
  }
  
  return {
    // state
    deviceType: readonly(deviceType),
    loading: readonly(loading),
    selectedDate: readonly(selectedDate),
    sidebarCollapsed: readonly(sidebarCollapsed),
    
    // getters
    isMobile,
    isDesktop,
    
    // actions
    setDeviceType,
    setLoading,
    setSelectedDate,
    toggleSidebar,
    init,
    destroy
  }
})
